package com.gdatacloud.flow.controller;

//import com.gdata.base.facade.R;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.ui.modeler.domain.Model;
import org.flowable.ui.modeler.repository.ModelRepository;
import org.flowable.ui.modeler.serviceapi.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/flowable")
public class ModelerController {


    @Autowired
    protected ModelRepository modelRepository;
    @Autowired
    ProcessEngine processEngine;
    @Autowired
    ModelService modelService;
    @Autowired
    RepositoryService repositoryService;

    /**
     * 通过modelId部署流程
     */
    @GetMapping("/deploy")
    public String deploymentProcessDefinition(String modelId){
        if (modelId == null){
            return "流程模型不存在";
        }
        Model model = modelService.getModel(modelId);
        BpmnModel bpmnModel = modelService.getBpmnModel(model);
        repositoryService.createDeployment().name(model.getName())
                .addBpmnModel(model.getKey() + ".bpmn", bpmnModel)
                .deploy();
        return "部署成功";
    }
    /**
     * 查看xml
     */
    @GetMapping("/getXML/{modelId}")
    public void loadXmlByModelId(@PathVariable String modelId, HttpServletResponse response) {
        try {
            Model model = modelService.getModel(modelId);
            byte[] b = modelService.getBpmnXML(model);
            response.setHeader("Content-type", "text/xml;charset=UTF-8");
            response.getOutputStream().write(b);
        } catch (Exception e) {
           // LOGGER.error("ApiFlowableModelResource-loadXmlByModelId:" + e);
            e.printStackTrace();
        }
    }

    /**
     * 查看图片
     */
    @GetMapping("/getPNG/{modelId}")
    public void loadPngByModelId(@PathVariable String modelId, HttpServletResponse response) {
        Model model = modelService.getModel(modelId);
        RepositoryService repositoryService = processEngine.getRepositoryService();
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(model.getKey())
                .orderByProcessDefinitionVersion()//按版本
                .desc()//降序排列
                .list();
        if (list.size() <= 0 || list == null){
            return;
        }
        //获取最新版,防止多次部署,取图片报错
        ProcessDefinition processDefinition = list.get(0);
        //获取部署id
        String deploymentId = processDefinition.getDeploymentId();
        InputStream is = repositoryService.getResourceAsStream(deploymentId, processDefinition.getDiagramResourceName());
        try {
            response.setHeader("Content-Type", "image/png");
            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b, 0, 1024)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
        } catch (Exception e) {
          //  LOGGER.error("ApiFlowableModelResource-loadPngByModelId:" + e);
            e.printStackTrace();
        }
    }


}
